package com.yds.developtools.utils;

import android.app.Application;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;

import java.util.HashMap;
import java.util.Map;

/**
 * DownloadManager 下载文件帮助类
 *
 * 使用方法：
 *  // 初始化
 *  YDSDownloadHelper downloadHelper = YDSDownloadHelper.getInstance(getApplication());
 *
 *  // 开始下载
 *  downloadHelper.downloadFile(url, "MediaCreationTool_22H2.exe", new YDSDownloadHelper.DownloadListener() {
 *      @Override
 *      public void onProgress(long downloadId, int progress) {
 *          // 更新 UI 显示下载进度
 *          Log.i("YDSimon", "下载进度: " + progress + "%");
 *      }
 *
 *      @Override
 *      public void onDownloadSuccess(long downloadId) {
 *          // 下载成功
 *          Log.i("YDSimon", "下载成功, ID: " + downloadId);
 *      }
 *
 *      @Override
 *      public void onDownloadFailed(long downloadId) {
 *          // 下载失败
 *          Log.i("YDSimon", "下载失败, ID: " + downloadId);
 *      }
 *  });
 */
public class YDSDownloadFileSystemHelper {

    private static YDSDownloadFileSystemHelper instance;
    private final DownloadManager downloadManager;
    private final Map<Long, DownloadListener> downloadListeners; // 存储下载 ID 和对应的监听器
    private final Application context;
    private BroadcastReceiver downloadReceiver;

    private YDSDownloadFileSystemHelper(Application context) {
        this.context = context;
        this.downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        this.downloadListeners = new HashMap<>();
        registerReceiver();
    }

    public static synchronized YDSDownloadFileSystemHelper getInstance(Application context) {
        if (instance == null) {
            instance = new YDSDownloadFileSystemHelper(context);
        }
        return instance;
    }

    /**
     * 下载文件 - 默认下载到Download文件夹
     *
     * @param url      下载文件的 URL
     * @param fileName 下载文件的名称 如：hello.txt
     * @param listener 下载监听器
     */
    public void downloadFile(String url, String fileName, DownloadListener listener) {
        downloadFile(url, Environment.DIRECTORY_DOWNLOADS, fileName, listener);
    }

    /**
     * 下载文件 - 自定义文件夹 如：Environment.DIRECTORY_XXX
     *
     * @param url      下载文件的 URL
     * @param filePath 下载文件的路径 默认：Environment.DIRECTORY_DOWNLOADS
     * @param fileName 下载文件的名称 如：hello.txt
     * @param listener 下载监听器
     */
    public void downloadFile(String url, String filePath, String fileName, DownloadListener listener) {
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.setDestinationInExternalPublicDir(filePath, fileName);

        long downloadId = downloadManager.enqueue(request);
        downloadListeners.put(downloadId, listener); // 将下载 ID 和监听器关联

        new Thread(new DownloadProgressRunnable(downloadId)).start();
    }

    /**
     * 注册广播接收器，监听下载完成事件
     */
    private void registerReceiver() {
        downloadReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                long receivedDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                if (downloadListeners.containsKey(receivedDownloadId)) {
                    DownloadListener listener = downloadListeners.get(receivedDownloadId);
                    DownloadManager.Query query = new DownloadManager.Query();
                    query.setFilterById(receivedDownloadId);
                    Cursor cursor = downloadManager.query(query);
                    if (cursor.moveToFirst()) {
                        int statusIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
                        int status = cursor.getInt(statusIndex);
                        if (status == DownloadManager.STATUS_SUCCESSFUL) {
                            if (listener != null) {
                                listener.onDownloadSuccess(receivedDownloadId);
                            }
                        } else if (status == DownloadManager.STATUS_FAILED) {
                            if (listener != null) {
                                listener.onDownloadFailed(receivedDownloadId);
                            }
                        }
                    }
                    cursor.close();
                    downloadListeners.remove(receivedDownloadId); // 下载完成后移除监听器
                }
            }
        };

        IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        context.registerReceiver(downloadReceiver, filter);
    }

    /**
     * 下载进度检查线程
     */
    private class DownloadProgressRunnable implements Runnable {
        private final long downloadId;

        DownloadProgressRunnable(long downloadId) {
            this.downloadId = downloadId;
        }

        @Override
        public void run() {
            while (true) {
                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(downloadId);
                Cursor cursor = downloadManager.query(query);
                if (cursor.moveToFirst()) {
                    int statusIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
                    int status = cursor.getInt(statusIndex);
                    if (status == DownloadManager.STATUS_SUCCESSFUL || status == DownloadManager.STATUS_FAILED) {
                        cursor.close();
                        break; // 下载完成或失败时退出循环
                    }

                    int bytesDownloadedIndex = cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
                    int bytesTotalIndex = cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
                    int bytesDownloaded = cursor.getInt(bytesDownloadedIndex);
                    int bytesTotal = cursor.getInt(bytesTotalIndex);

                    if (bytesTotal > 0) {
                        int progress = (int) ((bytesDownloaded * 100L) / bytesTotal);
                        // 回调进度
                        if (downloadListeners.containsKey(downloadId)) {
                            DownloadListener listener = downloadListeners.get(downloadId);
                            if (listener != null) {
                                listener.onProgress(downloadId, progress);
                            }
                        }
                    }
                }
                cursor.close();

                try {
                    Thread.sleep(200); // 每秒检查一次下载进度
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 释放资源，注销广播接收器
     */
    public void release() {
        if (downloadReceiver != null) {
            context.unregisterReceiver(downloadReceiver);
            downloadReceiver = null;
        }
    }

    /**
     * 下载监听器接口
     */
    public interface DownloadListener {
        void onProgress(long downloadId, int progress); // 下载进度回调

        void onDownloadSuccess(long downloadId); // 下载成功回调

        void onDownloadFailed(long downloadId); // 下载失败回调
    }
}
